package org.videopractice.network;

import org.videopractice.common.Logger;
import org.videopractice.network.message.Message;

import io.netty.channel.Channel;

public class ServerManager<T> {

    public void sendMessageToAll(Message message) {
        for(IoSession ioSession : ChannelManager.allSession()) {
            sendMessageNoCache(ioSession.channel, message);
        }
    }

    public void sendMessageNoCache(Channel channel, Message message) {
        if (message == null || channel == null)
            return;
        this.sendMessage(channel, message);
    }

    public void sendMessage(Channel channel, Message message) {
        // 获取session,用于记录发送报文的内容
        IoSession session = ChannelManager.getSession(channel);
        Logger.i(String.format("发送消息：[%s, %s, %s]-%s", session.getAccount(), session.ipAddress, channel.id(), message));
        try {
            channel.writeAndFlush(message);
        } catch (Exception e) {
            Logger.i(String.format("发送消息[%s],失败", message.getMsgId()));
            // 重发机制
        }
    }

    public void logout(Channel channel) {
        // 注销通道，包括session
        ChannelManager.unregisterContext(channel);
    }
} 
